<template>
  <el-card>
    <div slot="header">
      <el-row type="flex" justify="space-between" align="middle">
        <h3>准入完善SKU售价信息</h3>
        <BtnRender :render="renderBtnsBar" />
      </el-row>
    </div>
    <div v-loading="TableInfo.loading">
      <el-row class="info-wrap">
        <el-col :span="6">
          <span>状态：{{ detailsInfo.state }}</span>
        </el-col>
        <el-col :span="6">
          <span>管理区域：{{ detailsInfo.manageAreaName }}</span>
        </el-col>
        <el-col :span="12">
          <span>商品名称：{{ detailsInfo.productName }}</span>
        </el-col>
      </el-row>
      <SkusTable
        ref="skusTable"
        :tableHeight="480"
        :defaultMinWidth="100"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
      />
    </div>
  </el-card>
</template>
<script>
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import { TABLE_COLUMNS } from '../../constants/skuToBePerfect/skuPriceInfo';
import {
  getInitSaleDetails,
  processFrontendValidateResultsAdd,
  processBackendValidateResults,
  getSalesWithoutMessage
} from '@/utils/salePrice';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import { TableInfo } from '@/utils/getUtils';
import { createExcelByExport, generateUuid, isResponseSuccess } from '@/utils/bizUtils';
import {
  getInitDataForAddSkuService,
  saveForAddSkuService
} from '@/api/commodity/prepareSalePrice/prepareSku';
import {
  exportExcelService,
  importExcelUrl
} from '@/api/commodity/prepareSalePrice/prepareSpu';
export default {
  components: {
    BtnRender,
    SkusTable
  },
  data () {
    return {
      detailsInfo: {},
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      btnLoading: {
        export: false,
        submit: false
      },
    }
  },
  mounted () {
    const { productUuid } = this.$route?.query
    this.setInitData(productUuid)
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnsBar = [
        { label: '返回', method: this.handleGoBack, type: 'default' },
        {
          label: '模板导入',
          action: importExcelUrl,
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: this.TableInfo.setLoading
        },
        {
          label: '模板导出',
          method: this.handleExport,
          loading: this.btnLoading.export,
          disabled: this.TableInfo.isNullList()
        },
        {
          label: '提交',
          method: this.handleSubmit,
          loading: this.btnLoading.submit,
          disabled: this.TableInfo.isNullList()
        }
      ]
      return getListPageBtnsBar(h, btnsBar)
    },
    // 设置初始数据
    async setInitData (productUuid) {
      const data = { productUuid }
      const res = await getInitDataForAddSkuService(data, this.TableInfo.setLoading)
      if (res?.retData) {
        this.TableInfo.setList(getInitSaleDetails(res.retData))
        this.setDetailsInfo(res.retData)
      }
    },
    // 设置详情信息
    setDetailsInfo (retData) {
      const { manageAreaName = '', productName = '' } = retData[0] ?? {}
      this.detailsInfo = {
        state: this.$route?.query?.addStateStr,
        manageAreaName,
        productName
      }
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: 'skuToBePerfectList' })
    },
    // 模板导入 - 不需要重新计算售价（以导入数据为准）
    handleUploadSuccess (res) {
      if (isResponseSuccess(res)) {
        this.TableInfo.setList(res.retData)
      }
    },
    // 模板导出
    async handleExport () {
      const uuid = generateUuid()
      const data = { uuid, sales: this.TableInfo.list }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportExcelService(data, loadingFn)
      createExcelByExport({ excelTitle: `批量新增售价_${uuid}`, res })
    },
    // 提交
    handleSubmit () {
      processFrontendValidateResultsAdd(this.TableInfo.list, callbackArgs => {
        if (!callbackArgs) return this.fetchSubmitPriceList()
        const { list, columns, submitFlag } = callbackArgs
        this.TableInfo.setList(list)
        this.TableInfo.setColumns([...columns, ...TABLE_COLUMNS])
        if (submitFlag) this.fetchSubmitPriceList(submitFlag)
      })
    },
    // 提交请求
    async fetchSubmitPriceList (submitFlag) {
      const data = {
        submitFlag,
        sales: getSalesWithoutMessage(this.TableInfo.list)
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await saveForAddSkuService(data, loadingFn)
      const ErrorMaps = res?.retData ?? {}
      const executeSuccessSubmitTask = () => {
        this.$message.success('提交成功')
        this.handleGoBack()
      }
      processBackendValidateResults(this.TableInfo.list, ErrorMaps, callbackArgs => {
        if (!callbackArgs) return executeSuccessSubmitTask()
        const { list, columns, submitFlag } = callbackArgs
        this.TableInfo.setList(list)
        this.TableInfo.setColumns([...columns, ...TABLE_COLUMNS])
        if (submitFlag) this.fetchSubmitPriceList(submitFlag)
      })
    }
  }
}
</script>
